설치한 패키지

# install.packages("readxl")      # 엑셀파일 읽기.
# install.packages("writexl")     # 엑셀파일 쓰기.
# install.packages("tidyverse")   # dplyr, ggpplot2, tidyr, readr, purrr, tibble, forcats, stringr
# install.packages("e1071")       # 첨도와 왜도 구하기
# install.packages("epiDisplay")  # 그래프와 빈도표를 한번에 그려줌
# install.packages("psych")       # 양적자료를 한번에 계산해줌.
# install.packages("DataExplorer")# 자료의 데이터를 보고서형태로 나타내거나 여러 그림자료로 보여줌
# install.packages("gmodels")     # 크로스테이블 작성시??
# install.packages("GGally")      # 산점행렬도
# install.packages("officer")     # 분석결과를 ppt로 작성해줌

패키지 적용

library(readxl)
library(writexl)
library(tidyverse)
## -- Attaching packages ---- tidyverse 1.2.1 --
## √ ggplot2 3.2.1     √ purrr   0.3.2
## √ tibble  2.1.3     √ dplyr   0.8.3
## √ tidyr   1.0.0     √ stringr 1.4.0
## √ readr   1.3.1     √ forcats 0.4.0
## -- Conflicts ------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(e1071)
library(epiDisplay)
## Loading required package: foreign
## Loading required package: survival
## Loading required package: MASS
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
## Loading required package: nnet
## 
## Attaching package: 'epiDisplay'
## The following object is masked from 'package:ggplot2':
## 
##     alpha
library(psych)
## 
## Attaching package: 'psych'
## The following objects are masked from 'package:epiDisplay':
## 
##     alpha, cs, lookup
## The following objects are masked from 'package:ggplot2':
## 
##     %+%, alpha
library(DataExplorer)
library(gmodels)
## 
## Attaching package: 'gmodels'
## The following object is masked from 'package:epiDisplay':
## 
##     ci
library(GGally)
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
## 
## Attaching package: 'GGally'
## The following object is masked from 'package:dplyr':
## 
##     nasa

1일차


1 . 연산자


R 은 대소문자 구분을 한다!

(1) 산술연산자


+, -, /, * **, ^, %%, %/%
과거에는 메모리 문제로 한줄에 여러 명령어를 썼으나 현재는 메모리 성능의 향상으로 여러줄로 나누어 쓴다.

3+4   # 더하기
## [1] 7
3-4   # 빼기
## [1] -1
3*4   # 곱하기
## [1] 12
3/4   # 나누기
## [1] 0.75
3**4  # 거듭제곱
## [1] 81
3^4   # 거듭제곱
## [1] 81
13%%4 # 나머지
## [1] 1
13%/%4# 몫
## [1] 3


(2) 할당연산자

저장하는 기능 <-, =, -> <-, -> : 일반적인 저장기능 = 함수의 argument 지정하는 기능

x <- rnorm(n =100, mean = 10, sd = 2)

rnorm() : 평군이 10이고 표준편차가 2인 리스트를 n개 생성 n , mean, sd = argument

(3) 비교연산자


!, >, >=, <, <=, ==, !=

(4) 논리연산자

& , | & : and - 여러개의 조건을 동시에 만족해야함 | : or - 여러개의 조건 중 하나라도 만족해야함

2. 데이터의 유형(Type of Data)


(1) 수치형


  1. 정수 (integer)
  2. 실수 (double)
x1 <- 10
x2 <- 10.2
typeof(x1)
## [1] "double"
typeof(x2)
## [1] "double"


(2) 문자형 (Character)

x3 <- '문자열은'
x4 <- 'Character'
typeof(x3)
## [1] "character"
typeof(x4)
## [1] "character"


(3) 논리형 (Logical)

x5 <- TRUE
x6 <- FALSE
typeof(x5)
## [1] "logical"
typeof(x6)
## [1] "logical"


3.Data


(1) vector

  • 집단으로 인식되지 않는 열의 원소들
  • 하나의 열로 구성되며 1차원 구조를 가짐.
  • 하나의 데이터 유형만을 가지며 데이터 분석의 기본단위가 된다.

vector 만들기

  1. c(element, element, ….) c: combine or concatenate의 약자 numberic, character, logical vector을 만듬 element간의 규칙이 존재하지 않을때 사용
age <- c(20,30,24,25,31)
typeof(age)
## [1] "double"
bt <- c("a","b","ab","o")
typeof(bt)
## [1] "character"
smoke <- c(FALSE,TRUE)
typeof(smoke)
## [1] "logical"


ii. : numberic vector 만 만들수 있음. 1씩 증가 혹은 감소하는 숫자들로 구성. start:end start < end : 1씩 증가 start > end : 1씩 감소

test1 <- 1:10
test2 <- 10:1


iii. seq(from = , to = , by = )

  seq: sequence의 약자
  numberic vector만 만들수 있음.
  등차수열만을 생성
  사실상 : 의 확장.
  form = start
  to   = end
  by   = interval
<br>  
id1 <- seq(from = 1, to = 10,by = 2)
typeof(id1)
## [1] "double"
id2 <- seq(from = 10, to = 1, by = -2)
typeof(id2)
## [1] "double"


vector의 속성

i. element 의 갯수.
  - length(vector)
  
ii 데이터의 유형
  - mode(vector)
  
iii element 이름
  - names(vector)
    - 처음 벡터를 생성하면 이름값은 null이다.
    - null :  값이 존재하지 않는다. 즉, object가 존재하지 않는다.
    - 이름 설정 방법
      - names(vector) <- c(name,name,name...)
    - 이름 삭제
      - names(vector) <- NULL


vector 의 index

  • element의 위치. # 첫번째 element의 위치는 1(자바나 파이썬에서는 0이다.)

vector 의 slicing

-vector[index]

vector의 산술연산

  • index가 같은 원소끼리 연산한다.
  • 특징
    • vectorization : 벡터화
    • recycling Rule(재사용 규칙) : iterate 와 같이 연산시 더 짧은 벡터를 반복하여 사용한다.
      • 파이썬의 itertools 라고 생각하면 편함.

(2) Factor

  - 집단으로 구성될 수있는 열의 원소들
  - 하나의 열로 구성되어 있으며, 1차원 구조이다.
  - 하나의 데이터 유형만을 가지며 데이터 분석의 기본단위로 사용된다.

vector 만들기.

  • factor(vector,labels= , levels= , ordered = )
  • 즉, vector에 이름과 순서를 부여하고, 같은 내역끼리 묶을 수 있도록 만든것이 factor이다.

vector 속성

i. 집단의 갯수: nlevels(factor)
ii. 집단의 이름과 순서 : levels(factor)

(3) Data.Frame

  - 행렬구조로 이루어진 데이터 집합
  - 2차원 구조
  - 열마다 다른 데이터 유형을 지닐 수 있음.
  - R 에서 data라고 지칭하는 것들
  - matrix와의 차이는 matrix는 모든 열의 데이터 타입이 같아야 한다.
  - 참고 : tibble, data.table는 data.frame와 유사한 구조를 지닌다.
  
  

data.frame 만들기

  - data.frame(vector,vector,factor,vector....)
  
  

(4) List

  - 가장 유연한 형태의 데이터
  - 1차원 구조로 vector, factor, data.frame, list를 element로 가질 수 있음.
  - element의 size가 모두 다를 수 있다. 즉, 데이터의 크기가 유연하다.
  - 데이터 분석의 결과는 보통 리스트로 나타남

list 만들기

  - list(vector, factor, data.frame,list,....)
  

list의 slicing

2~3일차

file I/O

1. txt

separator : blank

- data_name <- read.table(file   = "directory/filename.txt",
                            header = TRUE,
                            sep    = " " or "," or "\t")
- write.table(data,
              file      = "directory/filename.txt",
              sep       = " " or "," or "\t",
              row.names = FALSE or TRUE)
- file   = 파일 위치
- header = 첫 행이 자료의 인덱스인지 값인지를 확인
- sep    = separator -> 문서를 data.frame 형태로 가공할 때 사용되는 구분자를 정함
- row.names = 첫행이 element의 이름인지 아닌지를 판단.  

2. csv

- csv : comma separated value
- 엑셀파일의 특수한 형태
- data_name <- read.csv(file   = "directory/filename.csv",
                       header = TRUE)
- write.csv(data,
            file = " directory/filename.csv",
            row.names = FALSE or TRUE)
- file   = 파일 위치
- header = 첫 행이 자료의 인덱스인지 값인지를 확인
- sep : csv가 기본적으로 , 를 구분자로 지원하기 때문에 존재하지 않는다.
- row.names = 첫행이 element의 이름인지 아닌지를 판단.

3. excel

- R 의 기본기능에서는 존재하지 않는다.
- readxl : 엑셀파일을 읽어옴
    - data_name <- readxl::read_excel(path      = "directory/filename.xlsx",
                                      sheet     = "sheet_name" or sheet_index,
                                      col_names = TRUE)
- writexl : 엑셀파일로 내보냄
    - data_name <- writexl::write_xlsx(path     = "directory/filename.xlsx")

4. RData

- 저장하기
  - save(data,file = "directory/filename.RData")
- 불러오기
  - load(file = "directory/filename.RData")
    
    

작업공간 설정하기

- (1) 현재 설정된 작업공간 : getwd()
- (2) 새로운 작업공간 설정하기 : setwd("directory")


데이터 읽어오기

- 예제 데이터 : ggplot2::diamonds

1.데이터 전체보기

- (1) View(data)
- (2) data
  - 콘솔에 출력됨, 데이터가 작을때 주로 사용
    

2.데이터 일부보기

- (1) head(data, n= n)
  - 콘솔에 출력이 됨,데이터의 위에서부터 n개만큼 출력
- (2) tail(data, n=n)
  - 콘솔에 출력이 됨,데이터의 아래에서부터 n개만큼 출력
  

3.데이터의 구조보기

- (1) str(data)
- (2) dplyr::glimpse(data)
    dplyr::glimpse(diamonds)
## Observations: 53,940
## Variables: 10
## $ carat   <dbl> 0.23, 0.21, 0.23, 0.29, 0.31, 0.24, 0.24, 0.26, 0.22, ...
## $ cut     <ord> Ideal, Premium, Good, Premium, Good, Very Good, Very G...
## $ color   <ord> E, E, E, I, J, J, I, H, E, H, J, J, F, J, E, E, I, J, ...
## $ clarity <ord> SI2, SI1, VS1, VS2, SI2, VVS2, VVS1, SI1, VS2, VS1, SI...
## $ depth   <dbl> 61.5, 59.8, 56.9, 62.4, 63.3, 62.8, 62.3, 61.9, 65.1, ...
## $ table   <dbl> 55, 61, 65, 58, 58, 57, 57, 55, 61, 61, 55, 56, 61, 54...
## $ price   <int> 326, 326, 327, 334, 335, 336, 336, 337, 337, 338, 339,...
## $ x       <dbl> 3.95, 3.89, 4.05, 4.20, 4.34, 3.94, 3.95, 4.07, 3.87, ...
## $ y       <dbl> 3.98, 3.84, 4.07, 4.23, 4.35, 3.96, 3.98, 4.11, 3.78, ...
## $ z       <dbl> 2.43, 2.31, 2.31, 2.63, 2.75, 2.48, 2.47, 2.53, 2.49, ...
    diamonds %>% 
      dplyr::glimpse()
## Observations: 53,940
## Variables: 10
## $ carat   <dbl> 0.23, 0.21, 0.23, 0.29, 0.31, 0.24, 0.24, 0.26, 0.22, ...
## $ cut     <ord> Ideal, Premium, Good, Premium, Good, Very Good, Very G...
## $ color   <ord> E, E, E, I, J, J, I, H, E, H, J, J, F, J, E, E, I, J, ...
## $ clarity <ord> SI2, SI1, VS1, VS2, SI2, VVS2, VVS1, SI1, VS2, VS1, SI...
## $ depth   <dbl> 61.5, 59.8, 56.9, 62.4, 63.3, 62.8, 62.3, 61.9, 65.1, ...
## $ table   <dbl> 55, 61, 65, 58, 58, 57, 57, 55, 61, 61, 55, 56, 61, 54...
## $ price   <int> 326, 326, 327, 334, 335, 336, 336, 337, 337, 338, 339,...
## $ x       <dbl> 3.95, 3.89, 4.05, 4.20, 4.34, 3.94, 3.95, 4.07, 3.87, ...
## $ y       <dbl> 3.98, 3.84, 4.07, 4.23, 4.35, 3.96, 3.98, 4.11, 3.78, ...
## $ z       <dbl> 2.43, 2.31, 2.31, 2.63, 2.75, 2.48, 2.47, 2.53, 2.49, ...

4.입력오류 체크하기

- summary(data)
- data %>% summary()
  
  

5.데이터의 속성

- 데이터 : data.frame, tibble, data.table
- (1) 행의 갯수
  - nrow(data)
nrow(diamonds)
## [1] 53940
diamonds %>% 
  nrow()
## [1] 53940
- (2) 열 = 변수 = Feature의 갯수
  - ncol(data)
diamonds %>% 
  ncol()
## [1] 10
- (3) 열 = 변수 = Feature의 이름
  - colnames(data)
diamonds %>% 
  colnames()
##  [1] "carat"   "cut"     "color"   "clarity" "depth"   "table"   "price"  
##  [8] "x"       "y"       "z"

6. Data의 Slicing

- data[row_index,col_index]

(1) 열 = 변수 = Feature

  - dplyr::select(data, variable, ...)
diamonds %>% 
  dplyr::select(carat,y,z) -> diamondsDF #변수를 뽑아와서 diamondsDF에 이름 저장
  - cut ~ y 열 잘라서 저장
diamonds %>% 
  dplyr::select(cut:z)
  - color을 제외한 나머지 열
diamonds %>% 
  dplyr::select(-color)
  - cut~y를 제외한 나머지 열
diamonds %>% 
  dplyr::select(-(cut:z))
- 변수명에 패턴이 있는 경우
  i. 변수명에 특정한 문자를 포함(contains())
diamonds %>% 
  dplyr::select(contains("c"))
  ii. 특정한 문자로 시작하는 경우(starts_with())
diamonds %>% 
  dplyr::select(starts_with("c"))
  iii. 특정한 문자로 끝나는 경우(ends_with())
diamonds %>% 
  dplyr::select(ends_with("e"))

(2) 행

- dplyr::filter(data,조건)
  - 비교연산자를 사용
diamonds %>% 
  dplyr::filter(carat >= 2)

(3) 행과 열

diamonds %>% 
  dplyr::filter(carat >= 2, cut == "Fair") %>% 
  dplyr::select(x:z)

7. 새로운 변수 만들기

- 열을 만든다는 의미(dplyr::mutate(변수명 = element))

(1) 연산

- 기존 열의 연산으로 새로운 열의 원소를 채움
- ex) 더하기, 빼기, 평균값, 분산 등등

(2) 변환

- 데이터의 개형이 부적편포를 보일때 분석하기에 위험이 따르므로 <br> 
root,log,inverse 와 같은 연산을 통해 데이터의 개형을 정규분포에 <br>
가깝게 변환시키는 것을 의미한다.


(3) 범주를 줄이기

- 데이터의 범주가 너무 세분화 되어서 특정 범주의 데이터가 적을때,<br>
근처의 범주와 통합하여 분석할 범주를 줄이는 기법이다.

diamonds %>% 
  dplyr::mutate(cut_group = ifelse(cut == "Ideal","Ideal","NonIdeal"))
- dplyr::mutate(names = ifelse(조건,참일경우 출력값,거짓일 경우 출력값))

(4) 양적인 자료를 질적인 자료로 변경

- 양적자료 : 숫자로 이루어져 있으며 숫자에 의미가 있고 연산이 가능함.
- 질적자료 : 문자 혹은 숫자로 이루어져 있으며 숫자에 아무런 의미가 없고 연산이 불가능하다.

8. 메모리에 있는 데이터 목록보기 및 삭제

목록보기

- ls() : list segment의 약자

삭제하기

- rm(data1,data2,.....)
- rm(list = ls()) - 모두 삭제명령어이므로 우선적으로 RData로 내보내기 후 삭제하는것을 추천

9. 데이터 정렬하기

(1) vector, factor

- sort(data,decreasing = FALSE or TRUE)
  - decreasing = FALSE >> 오름차순
  - decreasing = TRUE  >> 내림차순
  

(2) data.frame or tibble, data.table

- dplyr::arrange(data,variable,desc(variable))

10. 데이터 합치기

(1) 위/아래

- rbind(data1,data2,.....)

(2) 왼쪽/오른쪽(1)

- cbind(data1,data2)

(3) 왼쪽/오른쪽(2)

- data.frame(data1,data2)
- i.   inner join
  dplyr::inner_join(data1,data2,by="primary_key")
- ii.  outer join : full join
  dplyr::full_join(data1,data2,by="primary_key")
- iii. outer join : left join
  dplyr::left_join(data1,data2,by="primary_key")
- iv.  outer join : right join
  dplyr::right_join(data1,data2,by="primary_key")

4~5일차

EDA : Exploratory Data Analysis

(1) 일변량 자료의 분석

- 일변량 : uni-variate = 하나의 열(하나의 변수)
- Y or X
- Y : Label
- X : Feature
- 질적 자료 - 범주형 자료 (ex.cut,color,clarity)
표(Table) = 빈도표(Frequency Table)
  - i.  빈도(Frequency)
  - ii. 백분률(Percent) = (빈도/합계)*100(%)
  
diamonds %>% 
  dplyr::group_by(cut) %>% 
  dplyr::summarise(n = n()) %>% 
  dplyr::mutate(percent = round((n/sum(n))*100,digits = 1)) %>% 
  dplyr::arrange(desc(n))
그래프
- (1) 막대그래프
  - ggplot2 를 사용하여 그래프를 그림.
  - ggplot2는 데이터를 파이프로 보내는 것이 아니라 뒤에 다른 기능을 덧붙이는 것이므로<br>
    "+" 기호를 사용하여 줄바꿈을 한다.
  - mapping     = x축 y축 선택
  - geom_xxx()  = 그래프 종류 선택
  - theme_xxx() = 그림영역 선택
  - labs()      = 제목
  - theme()     = 제목 편집
diamonds %>% 
  ggplot2::ggplot(mapping = aes(x = cut)) + 
  ggplot2::geom_bar(fill = "red") +                                # 그래프 종류 선택
  ggplot2::theme_classic() +                                       # 그래프 뒷배경 선택
  ggplot2::labs(title = "Quality of Diamonds",                     # 그래프 타이틀
                x     = "Cut",                                     # 그래프 x축 이름
                y     = "Frequency")+                              # 그래프 y출 이름
  ggplot2::theme(plot.title = element_text(size    = 20,           # 타이틀 폰트크기
                                           color   = "gray",       # 타이틀 글씨 색
                                           face    = "bold",       # 타이틀 글씨효과
                                           hjust   = 0.5),         # 타이틀 위치
                 axis.title.x = element_text(size  = 15,           # x축 제목 크기
                                             color = "blue",       # x축 제목 색
                                             face  = "italic",     # x축 제목 글씨효과
                                             hjust = 0.5),         # x축 제목 위치
                 axis.title.y = element_text(size  = 15,           # y축 제목 크기
                                             color = "blue2",      # y축 제목 색
                                             face  = "bold.italic",# y축 제목 글씨효과
                                             vjust = 0.5,          # y축 제목 위치
                                             angle = 0))           # y축 제목 기울기

+ gglopt2::ggsave(filename = “cut.jpeg”,width=10,height=10)
을 통해서 그래프를 저장할 수 있다.

(2) 일변량 양적자료의 분석

- 양적자료 = 수치형 자료
- ex) carat, depth, table, price, x, y, z
- i.  표 = 빈도표
    (1) 구간의 빈도
    (2) 구간의 백분률
diamonds %>% 
  dplyr::mutate(carat_group = cut(carat,
                                  breaks = seq(from=0,to=6,by=2),
                                  right = FALSE,
                                  labels = c("Light","Medium","Heavy"))) %>% 
  dplyr::group_by(carat_group) %>% 
  dplyr::summarise(n = n()) %>% 
  dplyr::mutate(percent = round((n/sum(n))*100,digits = 1))
그래프
- (1) 히스토그램(Histogram)
  - geom_histogram()
  - binwidth = 구간의 넓이
  - bins     = 구간의 개수
diamonds %>% 
  ggplot2::ggplot(mapping = aes(x = carat))+
  ggplot2::geom_histogram(binwidth = 0.3,bins = 50)

- (2) 상자그림 (Boxplot) - 이상치(outlier)가 존재하는지 파악할 때 사용하는 그래프 - 히스토그램은 이상치를 주관적으로 판단하지만, 상자그림은 객관적으로 판단한다. - outlier.color = 이상치를 색으로 표시

diamonds %>% 
  ggplot2::ggplot(mapping = aes(y = carat))+
  ggplot2::geom_boxplot(outlier.color = "red")

(3) 기술통계량 = 요약통계량

- 기술통계량 : descriptive statistics
- 요약통계량 : summary statistics
- (1) 중심 = 대표값 (평균, 절사평균,중위수,최빈수)
    - 평균

- 절사평균 - 중위수 - 최빈수 - (2) 퍼짐 = 산포 = 다름 *******(범위,사분위범위,표준편차,중위수 절대편차) - 데이터 분석의 핵심은 다름을 보기 위함이다. - 관심있는데이터의 다름을 본다는 것의 의미는 수치화(정량화) 한다는 것이다. - 수치의 중요도에 대한 판단이 중요하다. -> 무시할 수 없다면 다름의 발생 주체는 누구인가? - 범위 - 사분위 범위 - 표준편차 - 중위수 절대편차 - (3) 분포의 모양 - 왜도(skewness):대칭을 확인 - 첨도(kurtosis):뾰족한 정도를 확인 - (4) 최대값과 최소값 - min() - max() - (5) missing value가 있는 경우 - na.rm = TRUE 를 사용해서 결측치 제거

3. 모든 일변량 질적자료를 한 번에 분석하기

- epiDisplay = 그래프를 모두 그려줌.
diamonds %>% 
  purrr::keep(is.factor) %>% 
  purrr::map(epiDisplay::tab1)

## $cut
## .x[[i]] : 
##           Frequency Percent Cum. percent
## Fair           1610     3.0          3.0
## Good           4906     9.1         12.1
## Very Good     12082    22.4         34.5
## Premium       13791    25.6         60.0
## Ideal         21551    40.0        100.0
##   Total       53940   100.0        100.0
## 
## $color
## .x[[i]] : 
##         Frequency Percent Cum. percent
## D            6775    12.6         12.6
## E            9797    18.2         30.7
## F            9542    17.7         48.4
## G           11292    20.9         69.3
## H            8304    15.4         84.7
## I            5422    10.1         94.8
## J            2808     5.2        100.0
##   Total     53940   100.0        100.0
## 
## $clarity
## .x[[i]] : 
##         Frequency Percent Cum. percent
## I1            741     1.4          1.4
## SI2          9194    17.0         18.4
## SI1         13065    24.2         42.6
## VS2         12258    22.7         65.4
## VS1          8171    15.1         80.5
## VVS2         5066     9.4         89.9
## VVS1         3655     6.8         96.7
## IF           1790     3.3        100.0
##   Total     53940   100.0        100.0

4. 모든 일변량 양적 자료에 대한 기술 통계량을 한번에 계산하기

- psych::describe = 기술통계량을 모두 계산해줌.
- psych::describe(data,trim = 0.05)
    - 절사평균은 기본적으로 10퍼센트를 기준으로 하고 trim 옵션으로 조정 가능하다.
diamonds %>% 
  purrr::keep(is.numeric) %>% 
  purrr::map_dfr(psych::describe)

5. 한번에 EDA 하기

- DataExplorer
    - 참고 : https://cran.r-project.org/web/packages/DataExplorer/vignettes/dataexplorer-intro.html
    - plot_str  : 데이터의 구조를 보여줌
    - introduce : 데이터의 기본정보 행과 열을 보여줌.
    - plot_intro: 기본정보를 표로 보여줌
    - create_report : 위의 정보들을 토대로 html 파일로 레포트를 작성해줌.

6. 이변량(Bi-variate) 자료의 분석

- (1) 질적자료 vs 질적자료
  - i. 표 = 교차표(cross Table) = 분할표(contingency Table)
  - gmodels를 사용
gmodels::CrossTable(diamonds$cut,diamonds$color,
                    prop.r = TRUE, # 행 백분률
                    prop.c = TRUE, # 열 백분률
                    prop.t = TRUE) # 전체 백분률
## 
##  
##    Cell Contents
## |-------------------------|
## |                       N |
## | Chi-square contribution |
## |           N / Row Total |
## |           N / Col Total |
## |         N / Table Total |
## |-------------------------|
## 
##  
## Total Observations in Table:  53940 
## 
##  
##              | diamonds$color 
## diamonds$cut |         D |         E |         F |         G |         H |         I |         J | Row Total | 
## -------------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|
##         Fair |       163 |       224 |       312 |       314 |       303 |       175 |       119 |      1610 | 
##              |     7.607 |    16.009 |     2.596 |     1.575 |    12.268 |     1.071 |    14.772 |           | 
##              |     0.101 |     0.139 |     0.194 |     0.195 |     0.188 |     0.109 |     0.074 |     0.030 | 
##              |     0.024 |     0.023 |     0.033 |     0.028 |     0.036 |     0.032 |     0.042 |           | 
##              |     0.003 |     0.004 |     0.006 |     0.006 |     0.006 |     0.003 |     0.002 |           | 
## -------------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|
##         Good |       662 |       933 |       909 |       871 |       702 |       522 |       307 |      4906 | 
##              |     3.403 |     1.973 |     1.949 |    23.708 |     3.758 |     1.688 |    10.427 |           | 
##              |     0.135 |     0.190 |     0.185 |     0.178 |     0.143 |     0.106 |     0.063 |     0.091 | 
##              |     0.098 |     0.095 |     0.095 |     0.077 |     0.085 |     0.096 |     0.109 |           | 
##              |     0.012 |     0.017 |     0.017 |     0.016 |     0.013 |     0.010 |     0.006 |           | 
## -------------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|
##    Very Good |      1513 |      2400 |      2164 |      2299 |      1824 |      1204 |       678 |     12082 | 
##              |     0.014 |    19.258 |     0.333 |    20.968 |     0.697 |     0.090 |     3.823 |           | 
##              |     0.125 |     0.199 |     0.179 |     0.190 |     0.151 |     0.100 |     0.056 |     0.224 | 
##              |     0.223 |     0.245 |     0.227 |     0.204 |     0.220 |     0.222 |     0.241 |           | 
##              |     0.028 |     0.044 |     0.040 |     0.043 |     0.034 |     0.022 |     0.013 |           | 
## -------------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|
##      Premium |      1603 |      2337 |      2331 |      2924 |      2360 |      1428 |       808 |     13791 | 
##              |     9.634 |    11.245 |     4.837 |     0.473 |    26.432 |     1.257 |    11.300 |           | 
##              |     0.116 |     0.169 |     0.169 |     0.212 |     0.171 |     0.104 |     0.059 |     0.256 | 
##              |     0.237 |     0.239 |     0.244 |     0.259 |     0.284 |     0.263 |     0.288 |           | 
##              |     0.030 |     0.043 |     0.043 |     0.054 |     0.044 |     0.026 |     0.015 |           | 
## -------------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|
##        Ideal |      2834 |      3903 |      3826 |      4884 |      3115 |      2093 |       896 |     21551 | 
##              |     5.972 |     0.032 |     0.049 |    30.745 |    12.390 |     2.479 |    45.486 |           | 
##              |     0.132 |     0.181 |     0.178 |     0.227 |     0.145 |     0.097 |     0.042 |     0.400 | 
##              |     0.418 |     0.398 |     0.401 |     0.433 |     0.375 |     0.386 |     0.319 |           | 
##              |     0.053 |     0.072 |     0.071 |     0.091 |     0.058 |     0.039 |     0.017 |           | 
## -------------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|
## Column Total |      6775 |      9797 |      9542 |     11292 |      8304 |      5422 |      2808 |     53940 | 
##              |     0.126 |     0.182 |     0.177 |     0.209 |     0.154 |     0.101 |     0.052 |           | 
## -------------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|
## 
## 
  - ii. 막대그래프
      - x - x축, fill = y축
      - geom_bar() >> 기본 모양은 띠 막대모양
      - dodge 옵션을 넣으면 바그래프를 분할해서 나타내 준다.
diamonds %>% 
  ggplot2::ggplot(mapping = aes(x = cut, fill = color))+
  ggplot2::geom_bar(position = "dodge")

- 집단별 막대그래프

diamonds %>% 
  ggplot2::ggplot(mapping = aes(x = cut))+
  ggplot2::geom_bar()+
  ggplot2::facet_wrap(~color,nrow = 1,ncol = 7)

- 집단(R에서는 factor)은 무조건 질적자료이다 - nrow = 그래프를 보여주는 행의 갯수 - ncol = 그래프를 보여주는 열의 갯수 - diamonds %>%
ggplot2::ggplot(mapping = aes(x = cut))+
ggplot2::geom_bar()+
ggplot2::facet_wrap(~분석할 행의 이름을 넣는다 여러 행일때는 +연산을 사용,nrow = 1,ncol = 7) - (2) 질적자료 vs 양적자료 - 집단별 양적 자료의 분석 - (1) 집단별 히스토그램

diamonds %>% 
  ggplot2::ggplot(mapping = aes(x = carat))+
  ggplot2::geom_histogram(binwidth = 0.5)+
  ggplot2::facet_wrap(~cut+color,nrow = 5,ncol = 7)

- (2) 집단별 상자그림

diamonds %>% 
  ggplot2::ggplot(mapping = aes(x = cut))+
  ggplot2::geom_bar()+
  ggplot2::facet_wrap(~color,nrow = 1,ncol = 7)

- 품질별 상자그림 비교

diamonds %>% 
  ggplot2::ggplot(mapping = aes(x = carat, y = cut))+
  ggplot2::geom_boxplot(outlier.color = "red")

(3) 집단별 기술통계량

diamonds %>% 
  dplyr::summarise(n      = n(),
                   Mean   = mean(carat),
                   Median = median(carat),
                   SD     = sd(carat),
                   MAD    = mad(carat)) %>% 
  dplyr::arrange(desc(Mean))

또는

psych::describeBy(purrr::keep(diamonds,is.numeric),
                  group = diamonds$cut,
                  mat   = TRUE)
- (3) 양적자료 vs 양적자료
    - i.   그래프 : 산점도(scatter plot)
diamonds %>% 
  dplyr::sample_frac(size   = 0.1) %>%                  # 자료의 10퍼센트만 잘라서 샘플을 만듬.
  ggplot2::ggplot(mapping   = aes(x = carat,y = price))+
  ggplot2::geom_point(col   = "red",                    # 점의 색
                      size  = 0.5,                      # 점의 크기
                      shape = 2,                        # 점의 모양
                      alpha = 0.7)+                     # 점의 투명도
  ggplot2::facet_wrap(~cut)

- ii. 그래프 : 산점 행렬도(SPM : Scatter Plot MAtrix)

diamonds %>% 
  dplyr::sample_frac(size = 0.1) %>% 
  purrr::keep(is.numeric) %>% 
  GGally::ggpairs()

- iii. 상관계수(Coeffienct of Correlantion) - pearson의 상관계수 r - -1~1 사이의 값을 가짐. - |r| 이 1에 가까우면 강한 상관관계가 있다고 판단. - |r| 이 0에 가까우면 상관관계가 없다고 판단. - r의 부호가 +면 양의 상관관계 : x 가 증가하면 y도 증가 - r의 부호가 -면 음의 상관관계 : x 가 증가하면 y는 감소 - cor(data$variable,…, method = “pearson”)

cor(diamonds$carat,diamonds$price, method = "pearson")
## [1] 0.9215913

또는

diamonds %>% 
  purrr::keep(is.numeric) %>% 
  cor(method = "pearson") %>% 
  round(digits = 3)
##       carat  depth  table  price      x      y     z
## carat 1.000  0.028  0.182  0.922  0.975  0.952 0.953
## depth 0.028  1.000 -0.296 -0.011 -0.025 -0.029 0.095
## table 0.182 -0.296  1.000  0.127  0.195  0.184 0.151
## price 0.922 -0.011  0.127  1.000  0.884  0.865 0.861
## x     0.975 -0.025  0.195  0.884  1.000  0.975 0.971
## y     0.952 -0.029  0.184  0.865  0.975  1.000 0.952
## z     0.953  0.095  0.151  0.861  0.971  0.952 1.000

정리 완료 날짜 - 2019.11.08